package com.bzkj.inventory.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.model.LoginUser;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.core.page.TableDataInfoInvention;
import com.bzkj.common.domain.NccApiResponse;
import com.bzkj.common.utils.DataProcessCommonUtils;
import com.bzkj.common.utils.SecurityUtils;
import com.bzkj.common.utils.http.NccHttpUtils;
import com.bzkj.inventory.domain.InventoryCompareTask;
import com.bzkj.inventory.domain.InventoryDiscrepancyDetail;
import com.bzkj.inventory.domain.MaterialBatchKey;
import com.bzkj.inventory.domain.NccInventoryData;
import com.bzkj.inventory.domain.dto.CustconditionRequest;
import com.bzkj.inventory.domain.dto.InventoryQueryRequest;
import com.bzkj.inventory.domain.vo.NccInventory;
import com.bzkj.inventory.domain.vo.NccInventoryDataVo;
import com.bzkj.inventory.mapper.InventorySynMapper;
import com.bzkj.inventory.service.InventoryService;
import com.bzkj.inventory.utils.InventoryCompareUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

/**
 * @ClassName InventoryServiceImpl
 * @Description TODO
 * @Author C1309
 * @Date 2025/5/12 11:12
 */
@Service("inventoryService")
public class InventoryServiceImpl implements InventoryService {

    @Resource
    private NccHttpUtils nccHttpUtils;

    @Resource
    private InventorySynMapper inventorySynMapper;

    @Resource
    private PlatformTransactionManager transactionManager;

    @Resource
    @Qualifier("threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor executor;
    /**
     * NCC现存量查询接口
     */
    private final String NCC_QUERY_URL = "/nccloud/api/bqreport/report/query";

    @Value("${pk_org.uniqueCode}")
    private String pkOrgPk;

    /**
     * 自动核对WMS与NCC现存量定时任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synTheOnHandQuantityJob() {
        // 获取NCC仓库信息
        List<String> warehousePkList = inventorySynMapper.getWarehousePkList();
        if (warehousePkList.isEmpty()) {
            return;
        }

        List<CompletableFuture<Void>> futures = new ArrayList<>();

        for (String warehouseId : warehousePkList) {
            // 提交任务到线程池
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> processWarehouseWithTransaction(warehouseId), executor);
            futures.add(future);
        }

        try {
            // 等待所有任务完成（带超时控制）
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(60, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("任务被中断");
        } catch (ExecutionException e) {
            throw new RuntimeException("任务执行失败: " + e.getCause().getMessage());
        } catch (TimeoutException e) {
            throw new RuntimeException("任务执行超时");
        }
    }


    /**
     * 按仓库进行盘点
     *
     * @param warehouseId 仓库主键
     * @return 盘点结果
     */
    @Override
    public TableDataInfoInvention getInventoryList(String warehouseId, int pageSize, int pageNum) {
        List<CustconditionRequest> custcondition = createCustcondition(warehouseId);
        InventoryQueryRequest inventoryQueryRequest = new InventoryQueryRequest(custcondition);

        try {
            // 调用NCC现存量查询接口
            NccApiResponse nccApiResponse = nccHttpUtils.post(NCC_QUERY_URL, JSONObject.toJSONString(inventoryQueryRequest));
            // 校验NCC返回结果
            DataProcessCommonUtils.validateNccResponse(nccApiResponse);
            // 解析NCC返回结果
            NccInventoryDataVo nccInventoryDataVo = parseNccInventoryData(nccApiResponse);
            TableDataInfoInvention tableDataInfoInvention = new TableDataInfoInvention(new ArrayList<>(), 0);
            if (nccInventoryDataVo != null) {
                tableDataInfoInvention = startPageInfo(nccInventoryDataVo, pageNum, pageSize);
            }
            return tableDataInfoInvention;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存盘点结果
     *
     * @param warehouseId 仓库ID
     * @return 操作结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveInventoryData(String warehouseId) {
        List<CustconditionRequest> custcondition = createCustcondition(warehouseId);
        InventoryQueryRequest inventoryQueryRequest = new InventoryQueryRequest(custcondition);

        try {
            // 调用NCC现存量查询接口
            NccApiResponse nccApiResponse = nccHttpUtils.post(NCC_QUERY_URL, JSONObject.toJSONString(inventoryQueryRequest));
            // 校验NCC返回结果
            DataProcessCommonUtils.validateNccResponse(nccApiResponse);
            // 解析NCC返回结果
            NccInventoryDataVo nccInventoryDataVo = parseNccInventoryData(nccApiResponse);
            //存入库存数据
            assert nccInventoryDataVo != null;
            List<NccInventory> rows = nccInventoryDataVo.getRows();
            if (rows != null) {
                int index = 0;
                LoginUser loginUser = SecurityUtils.getLoginUser();
                String userName = loginUser.getUser().getUserName();
                for (NccInventory nccInventory : rows) {
                    inventorySynMapper.insertInventoryData(nccInventory, nccInventory.getCwarehouseId() + "-" + index++, userName, nccInventoryDataVo.getWarehouseId(), nccInventoryDataVo.getWarehouseName());
                }
                return 1;
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return 0;
    }

    /**
     * 手动同步WMS与NCC现存量
     *
     * @param warehouseIds 仓库ID
     * @return 消息提示
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 主方法事务（可选）
    public AjaxResult manualSyncingTheOnHandQuantity(String[] warehouseIds) {
        List<CompletableFuture<Void>> futures = new ArrayList<>();

        for (String warehouseId : warehouseIds) {
            // 提交任务到线程池
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> processWarehouseWithTransaction(warehouseId), executor);
            futures.add(future);
        }

        try {
            // 等待所有任务完成（带超时控制）
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(60, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("任务被中断");
        } catch (ExecutionException e) {
            throw new RuntimeException("任务执行失败: " + e.getCause().getMessage());
        } catch (TimeoutException e) {
            throw new RuntimeException("任务执行超时");
        }
        return AjaxResult.success("太棒啦！库存比对成功，请前往库存比对任务列表查看叭~");
    }

    // 独立事务处理方法（每个仓库一个事务）
    private void processWarehouseWithTransaction(String warehouseId) {
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.execute(status -> {
            try {

                return processWarehouse(warehouseId);
            } catch (Exception e) {
                status.setRollbackOnly(); // 异常时回滚
                throw e;
            }
        });
    }

    // 实际业务逻辑（线程安全处理）
    private Void processWarehouse(String warehouseId) {
        List<CustconditionRequest> custcondition = createCustcondition(warehouseId);
        InventoryQueryRequest request = new InventoryQueryRequest(custcondition);

        try {
            // 调用NCC接口
            NccApiResponse response = nccHttpUtils.post(NCC_QUERY_URL, JSONObject.toJSONString(request));
            DataProcessCommonUtils.validateNccResponse(response);

            // 解析数据
            NccInventoryDataVo nccData = parseNccInventoryData(response);
            List<NccInventory> nccList = Optional.ofNullable(nccData).map(NccInventoryDataVo::getRows).orElse(Collections.emptyList());

            // 查询WMS数据
            List<NccInventory> wmsList = inventorySynMapper.getWmsInventoryList(warehouseId);
            wmsList = wmsList == null ? Collections.emptyList() : wmsList;

            // 比对库存
            compareInventoryForWarehouse(nccList, wmsList);
        } catch (IOException e) {
            throw new RuntimeException("仓库[" + warehouseId + "]接口调用失败", e);
        }

        return null;
    }

    /**
     * 获取库存盘点调度日志
     *
     * @param warehouseId 仓库ID
     * @param startDate   开始日期
     * @param endDate     结束日期
     * @param isResolved  异常数量是否大于0（0为否，1为是）
     * @return 异常库存信息
     */
    @Override
    public TableDataInfo abnormalInventory(String warehouseId, Date startDate, Date endDate, String isResolved, int pageNum, int pageSize) {
        List<String> warehouseIds;
        if (warehouseId == null || warehouseId.trim().isEmpty()) {
            // 获取当前登录用户的用户ID
            Long userId = SecurityUtils.getLoginUser().getUserId();
            // 获取WMS管理并启用的仓库
            List<String> warehouseCodeList = inventorySynMapper.getWarehousePkList();
            // 获取用户管理的仓库
            List<String> userWarehouses = SecurityUtils.getLoginUser().getWarehouses().contains("*") ? warehouseCodeList : inventorySynMapper.getUserManageWarehouse(userId);
            warehouseIds = userWarehouses.stream().filter(warehouseCodeList::contains).collect(Collectors.toList());
        } else {
            warehouseIds = Collections.singletonList(warehouseId);
        }

        if (warehouseIds.isEmpty()) {
            return new TableDataInfo();
        }

        StringBuilder warehouseIdJoiner = new StringBuilder();
        for (String id : warehouseIds) {
            warehouseIdJoiner.append("'").append(id).append("',");
        }
        if (startDate == null && endDate == null) {
            // 获取系统默认时区的当前日期
            LocalDate today = LocalDate.now();

            // 当天的开始时间（00:00:00）
            LocalDateTime startOfDay = today.atStartOfDay();
            // 当天的结束时间（23:59:59）
            LocalDateTime endOfDay = today.atTime(LocalTime.of(23, 59, 59));

            // 转换为Date对象（如果需要）
            startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
            endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        }
        // 查询异常库存
        List<InventoryCompareTask> inventoryCompareTaskList = inventorySynMapper.getAbnoralInventory(warehouseIdJoiner.substring(0, warehouseIdJoiner.length() - 1), startDate, endDate, isResolved);
        return DataProcessCommonUtils.getTableInfo(inventoryCompareTaskList, pageNum, pageSize);
    }

    /**
     * 获取库存盘点异常信息
     *
     * @param taskId 任务ID
     * @return 库存异常盘点信息
     */
    @Override
    public List<InventoryDiscrepancyDetail> getInventoryDiscrepancyDetail(Long taskId) {
        List<InventoryDiscrepancyDetail> inventoryDiscrepancyDetailList = inventorySynMapper.getInventoryDiscrepancyDetail(taskId);
        return inventoryDiscrepancyDetailList == null ? Collections.emptyList() : inventoryDiscrepancyDetailList;
    }

    /**
     * 更新库存盘点任务ID
     *
     * @param taskId 任务ID
     * @return 更新结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTaskId(Long taskId) {
        String username = SecurityUtils.getLoginUser().getUsername();
        int i = inventorySynMapper.updateTaskId(taskId, username);
        if (i > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 获取库存盘点异常信息（导出用）
     *
     * @param ids 任务id
     * @return 库存盘点异常信息
     */
    @Override
    public List<InventoryDiscrepancyDetail> inventoryDiscrepancyDetailList(Long[] ids) {
        ArrayList<InventoryDiscrepancyDetail> inventoryDiscrepancyDetails = new ArrayList<>();
        for (Long id : ids) {
            System.out.println(id);
            List<InventoryDiscrepancyDetail> inventoryDiscrepancyDetailList = inventorySynMapper.getInventoryDiscrepancyDetail(id);
            inventoryDiscrepancyDetails.addAll(inventoryDiscrepancyDetailList);
        }
        return inventoryDiscrepancyDetails;
    }

    /**
     * 查询当前用户是否存在库存盘点异常信息
     *
     * @return 结果
     */
    @Override
    public int selectIsResolved() {
        // 获取系统默认时区的当前日期
        LocalDate today = LocalDate.now();

        // 当天的开始时间（00:00:00）
        LocalDateTime startOfDay = today.atStartOfDay();
        // 当天的结束时间（23:59:59）
        LocalDateTime endOfDay = today.atTime(LocalTime.of(23, 59, 59));

        // 转换为Date对象（如果需要）
        Date startDate = Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        TableDataInfo tableDataInfo = abnormalInventory(null, startDate, endDate, "1", 1, 1000);
        if (tableDataInfo == null || tableDataInfo.getRows() == null || tableDataInfo.getRows().isEmpty()) {
            return 0;
        }
        return 1;
    }


    /**
     * 创建查询条件
     *
     * @param warehouseId NCC仓库主键
     * @return 查询条件集合
     */
    private List<CustconditionRequest> createCustcondition(String warehouseId) {
        ArrayList<CustconditionRequest> custconditions = new ArrayList<>();
        CustconditionRequest dyngroupReport = new CustconditionRequest();
        CustconditionRequest pkOrg = new CustconditionRequest();
        CustconditionRequest cwarehouseid = new CustconditionRequest();

        dyngroupReport.setDataType("203");
        dyngroupReport.setKeyName("dyngroup_report");
        dyngroupReport.setTypeName("统计汇总口径");
        dyngroupReport.setOpt("=");
        dyngroupReport.setFirstValue("pk_org,cwarehouseid,clocationid,isLotno,isbatch,isAstunit,isStateid,isCvenderid,isProductorid,ishsl");
        dyngroupReport.setSecondValue("");

        pkOrg.setDataType("204");
        pkOrg.setKeyName("pk_org");
        pkOrg.setTypeName("库存组织");
        pkOrg.setOpt("=");
        pkOrg.setFirstValue(pkOrgPk);
        pkOrg.setSecondValue("");

        cwarehouseid.setDataType("204");
        cwarehouseid.setKeyName("cwarehouseid");
        cwarehouseid.setTypeName("仓库");
        cwarehouseid.setOpt("=");
        cwarehouseid.setFirstValue(warehouseId);
        cwarehouseid.setSecondValue("");

        custconditions.add(dyngroupReport);
        custconditions.add(pkOrg);
        custconditions.add(cwarehouseid);
        return custconditions;
    }

    /**
     * 解析NCC库存结果
     *
     * @param nccApiResponse NCC返回的库存结果
     * @return 解析结果
     */
    private NccInventoryDataVo parseNccInventoryData(NccApiResponse nccApiResponse) {
        if (nccApiResponse == null || nccApiResponse.getData() == null) {
            return new NccInventoryDataVo(); // 或返回 Optional.empty()
        }

        try {
            JSONArray jsonData = nccApiResponse.getData();
            List<NccInventoryData> nccInventoryDataList = jsonData.toList(NccInventoryData.class);

            if (nccInventoryDataList != null && !nccInventoryDataList.isEmpty()) {
                return aggregateInventoryData(nccInventoryDataList);
            }
            return new NccInventoryDataVo(); // 默认返回空对象
        } catch (JSONException | ClassCastException e) {
            return new NccInventoryDataVo(); // 或根据业务需求处理
        }
    }

    /**
     * 解析NCC库存数据
     *
     * @param inventoryList 库存数据
     * @return 解析结果
     */
    public NccInventoryDataVo aggregateInventoryData(List<NccInventoryData> inventoryList) {
        String warehouseId = inventoryList.get(0).getCwarehouseid();
        String warehouseName = inventoryList.get(0).getName2();
        // 定义复合键
        Map<MaterialBatchKey, List<NccInventoryData>> groupedInventory = inventoryList.stream().collect(Collectors.groupingBy(item -> new MaterialBatchKey(item.getCmaterialvid(), item.getPk_batchcode(), item.getVbatchcode(), item.getCproductorid())));

        List<NccInventory> resultList = new ArrayList<>();

        groupedInventory.forEach((key, items) -> {
            NccInventory vo = new NccInventory();
            // 设置物料、批次、批号信息、生产商信息
            vo.setPkMaterial(key.cmaterialvid);
            vo.setPkBatchCode(key.pk_batchcode);
            vo.setVbatchcode(key.vbatchcode);
            vo.setCproductorid(key.cproductorid);

            NccInventoryData firstItem = items.get(0);
            // 设置单位和生产商
            vo.setCunitid(firstItem.getName6());
            vo.setProductName(firstItem.getName8());

            // 处理日期字段
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            vo.setExpDate(formatDate(firstItem.getDvalidate1(), dateFormat));
            vo.setPdDate(formatDate(firstItem.getDproducedate1(), dateFormat));
            // 设置物料名称、单位pk、生产商pk
            vo.setMaterialName(firstItem.getName5());
            vo.setPkUnit(firstItem.getCunitid());
            vo.setVvendbatchcode(firstItem.getVvendbatchcode1());
            vo.setCwarehouseId(warehouseId);
            vo.setWarehouseName(warehouseName);
            vo.setSenderType(firstItem.getVdef_2());
            vo.setPackVersion(firstItem.getVdef_3());

            // 初始化数量字段
            initializeQuantityFields(vo);

            BigDecimal totalNum = new BigDecimal("0.0").setScale(5, RoundingMode.HALF_UP);
            for (NccInventoryData item : items) {
                BigDecimal num = parseNonHandNumRpt(item.getNonhandnumrpt());
                totalNum = totalNum.add(num).setScale(5, RoundingMode.HALF_UP);
                updateQuantityFields(vo, item.getCstateid(), num);
            }
            // 保留4位小数
            BigDecimal totalDecimal = totalNum.setScale(4, RoundingMode.HALF_UP);

            // 设置总数量并格式化
            vo.setSkuNum(totalDecimal);
            resultList.add(vo);
        });
        // 统计总库存数
        BigDecimal headerTotalNum = new BigDecimal("0.0").setScale(5, RoundingMode.HALF_UP);
        for (NccInventory nccInventory : resultList) {
            headerTotalNum = headerTotalNum.add(nccInventory.getSkuNum()).setScale(5, RoundingMode.HALF_UP);
        }
        // 保留4位小数

        NccInventoryDataVo nccInventoryDataVo = new NccInventoryDataVo();
        nccInventoryDataVo.setTotalNum(headerTotalNum.setScale(4, RoundingMode.HALF_UP));
        nccInventoryDataVo.setRows(resultList);
        nccInventoryDataVo.setWarehouseId(warehouseId);
        nccInventoryDataVo.setWarehouseName(warehouseName);
        nccInventoryDataVo.setTotal((long) resultList.size());
        return nccInventoryDataVo;
    }

    // 辅助方法：处理日期格式化
    private Date formatDate(String dateStr, SimpleDateFormat dateFormat) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        }
        try {
            return dateFormat.parse(dateStr); // 解析 String → Date
        } catch (Exception e) {
            return null; // 解析失败返回 null
        }
    }

    // 辅助方法：初始化数量字段为0
    private void initializeQuantityFields(NccInventory vo) {
        vo.setQualifiedNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
        vo.setUnqualifiedNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
        vo.setQuarantineNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
        vo.setLimitQualifiedNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
        vo.setSkunNoStateNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
        vo.setResearchNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
        vo.setQualifiedNoUseNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
        vo.setPendingNum(new BigDecimal("0.0").setScale(4, RoundingMode.HALF_UP));
    }

    // 辅助方法：解析数量字符串
    private BigDecimal parseNonHandNumRpt(String value) {
        if (value == null || value.trim().isEmpty()) {
            return new BigDecimal("0.0").setScale(5, RoundingMode.HALF_UP);
        }
        try {
            return new BigDecimal(value.trim()).setScale(5, RoundingMode.HALF_UP);
        } catch (NumberFormatException e) {
            return new BigDecimal("0.0").setScale(5, RoundingMode.HALF_UP);
        }
    }


    // 辅助方法：根据库存状态更新对应字段
    private void updateQuantityFields(NccInventory vo, String cstateid, BigDecimal num) {
        if (cstateid == null) {
            vo.setSkunNoStateNum(vo.getSkunNoStateNum().add(num).setScale(4, RoundingMode.HALF_UP));
            return;
        }
        switch (cstateid) {
            case "1001A110000000002T09":
                vo.setQualifiedNum(vo.getQualifiedNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
            case "1001ZZ1000000002XCX4":
                vo.setUnqualifiedNum(vo.getUnqualifiedNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
            case "1001A110000000002T08":
                vo.setQuarantineNum(vo.getQuarantineNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
            case "1001B1100000008N4LKD":
                vo.setLimitQualifiedNum(vo.getLimitQualifiedNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
            case "1001B110000000FNCCLS": //研究用
                vo.setResearchNum(vo.getResearchNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
            case "1001B110000000CMZGQ2": //合格不予上市
                vo.setQualifiedNoUseNum(vo.getQualifiedNoUseNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
            case "1001B1100000008HXPEP":
                vo.setPendingNum(vo.getPendingNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
            default:
                vo.setSkunNoStateNum(vo.getSkunNoStateNum().add(num).setScale(4, RoundingMode.HALF_UP));
                break;
        }
    }

    // 辅助方法：格式化数字保留两位小数
    private String formatNumber(double value) {
        DecimalFormat df = new DecimalFormat("#.00");
        return df.format(value);
    }

    /**
     * 辅助方法：库存比对
     *
     * @param nccList NCC库存列表
     * @param wmsList wms库存列表
     */
    public void compareInventoryForWarehouse(List<NccInventory> nccList, List<NccInventory> wmsList) {
        if (nccList.isEmpty() && wmsList.isEmpty()) {
            return;
        }
        NccInventory nccInventory;
        if (!nccList.isEmpty()) {
            nccInventory = nccList.get(0);
        } else {
            nccInventory = wmsList.get(0);
        }

        // 创建任务记录（父表）
        InventoryCompareTask task = new InventoryCompareTask();
        task.setWarehouseId(nccInventory.getCwarehouseId());
        task.setWarehouseName(nccInventory.getWarehouseName());
        task.setCompareTime(new Date());
        task.setResolved(false);
        task.setTotalDiscrepancy(0);
        inventorySynMapper.insertDiscrepancyTask(task); // 插入后主键回填


        // 执行比对（工具类处理逻辑）
        List<InventoryDiscrepancyDetail> detailList = InventoryCompareUtil.compare(nccList, wmsList, task.getId());

        // 插入子表
        if (!detailList.isEmpty()) {
            int size = detailList.size();
            int batchNum = size / 100 + 1;
            for (int i = 0; i < batchNum; i++) {
                int start = i * 100;
                int end = Math.min(start + 100, size);
                List<InventoryDiscrepancyDetail> batchList = detailList.subList(start, end);
                inventorySynMapper.insertBatch(batchList);
            }
            // 更新父表异常条数
            task.setTotalDiscrepancy(detailList.size());
            inventorySynMapper.updateTotalDiscrepancy(task.getId(), detailList.size());
        }
    }

    private String formatDouble(double value) {
        return String.format("%.2f", value);
    }

    /**
     * 分页封装
     *
     * @param pageNum  当前页码
     * @param pageSize 页大小
     * @return 分页数据
     */
    public TableDataInfoInvention startPageInfo(NccInventoryDataVo inventoryDataVo, int pageNum, int pageSize) {


        // 创建 TableDataInfo 对象
        TableDataInfoInvention tableDataInfo = new TableDataInfoInvention();
        List<NccInventory> rows = inventoryDataVo.getRows();

        // 分页计算
        int total = rows.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        // 检查分页范围
        if (fromIndex >= total) {
            tableDataInfo.setCode(200);
            tableDataInfo.setMsg("Oops~ 当前条件下没有找到单据，试试调整查询条件吧！");
            tableDataInfo.setRows(Collections.emptyList());
            tableDataInfo.setTotal(total);
            return tableDataInfo;
        }

        // 获取当前页数据
        List<NccInventory> pageData = rows.subList(fromIndex, toIndex);

        // 封装分页结果
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功！");
        tableDataInfo.setRows(pageData);
        tableDataInfo.setTotal(total);
        tableDataInfo.setTotalNum(inventoryDataVo.getTotalNum().toString());
        tableDataInfo.setWarehouseId(inventoryDataVo.getWarehouseId());
        tableDataInfo.setWarehouseName(inventoryDataVo.getWarehouseName());
        return tableDataInfo;
    }
}
